package com.example.demo.aop;

import com.example.demo.annotation.RateLimit;
import com.example.demo.common.ErrorCode;
import com.example.demo.exception.BusinessException;
import com.google.common.util.concurrent.RateLimiter;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class RateLimitAspect {

    private final RateLimiter rateLimiter;

    public RateLimitAspect(RateLimiter rateLimiter) {
        this.rateLimiter = rateLimiter;
    }

    @Around("@annotation(rateLimit)")
    public Object around(ProceedingJoinPoint point, RateLimit rateLimit) throws Throwable {
        if (!rateLimiter.tryAcquire()) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "请求过于频繁");
        }
        return point.proceed();
    }
} 